import os.path
import sys

# 使用这个列表管理学生
# 每个元素都是一个字典，每个字典表示一个学生的信息
studentList = []


def save():
    """
    用于存档
    :return:
    """
    # 此处写法（相对路径）表示当前路径是在该项目路径下
    with open("record.txt", "w", encoding="utf8") as f:
        for s in studentList:
            f.write(f"{s['sid']}\t{s['sname']}\t{s['gender']}\t{s['classid']}\n")
    print(f"存档成功,成功数据条数:{len(studentList)}")


def load():
    # 如果该文件不存在，就跳过读档
    if not os.path.exists("record.txt"):
        return
    # 开始读文件
    global studentList
    #先清理旧数据
    studentList = []
    with open('record.txt', 'r', encoding='utf8') as f:
        #先祛除换行
        for line in f:
            line = line.strip()
            tokens = line.split("\t")
            if len(tokens) != 4:
                print(f"当前行格式错误:{line}")
                continue
            student = {
                'sid': tokens[0],
                'sname': tokens[1],
                'gender': tokens[2],
                'classid': tokens[3]
            }
            studentList.append(student)
    print(f"读档成功，读档了{len(studentList)}条数据")



def menu():
    print("1.新增学生")
    print("2.查找学生")
    print("3.展示学生")
    print("4.删除学生")
    print("0.退出系统")
    choice = input("请输入您的操作:")
    return choice


def insert():
    print("新增学生开始~")
    sid = input("请输入学号:")
    sname = input("请输入学生姓名:")
    gender = input("请输入性别:")
    while gender not in ("男", "女"):
        gender = input("输入的性别错误，请重新输入:")
    classid = input("请输入学生的班级:")
    # 使用字典把这些信息组织起来
    student = {
        'sid': sid,
        'sname': sname,
        'gender': gender,
        'classid': classid
    }
    global studentList
    studentList.append(student)
    save()
    print("新增学生成功~")


def find():
    name = input("请输入待查找的学生姓名:")
    count = 0
    for s in studentList:
        if name == s['sname']:
            print(f"找到了[{s['sid']}]\t{s['sname']}\t{s['gender']}\t{s['classid']}\t!")
            count += 1
    print(f"共找到了{count}名匹配的同学~")


def display():
    print("开始展示学生~！")
    for s in studentList:
        print(f"[{s['sid']}]\t{s['sname']}\t{s['gender']}\t{s['classid']}\t")
    print(f"共打印了{len(studentList)}条数据!")


def delete():
    sid = input("请输入待删除学生的学号:")
    for s in studentList:
        if sid == s['sid']:
            studentList.remove(s)
            save()
            print("删除成功！")


def setUp():
    """
    入口函数
    """
    print("=================================")
    print("*         欢迎来到学生管理系统      *")
    print("=================================")
    load()
    while True:
        choice = menu()
        if choice == '1':
            insert()
        elif choice == '2':
            find()
        elif choice == '3':
            display()
        elif choice == '4':
            delete()
        elif choice == '0':
            print("good bye ~")
            sys.exit(0)
        else:
            print("********************")
            print("您的输入有误，请重新输入~")
            print("********************")


setUp()

# student = {
#         'sid',1,
#         'sname',2,
#         'gender',3,
#         'classid',4
#     }
# print(student.)
# ss = []
# ss.append(student)
# for s in ss:
#     print(s['sid'])
